


drop if female_w3 != female & female_w3 != .

* Belief blocks
local bel1 fob1 sob1 sob1sdb sob1m 
local bel2 fob2 sob2 sob2m sob2p
local bel3 fob3 sob3 sob3sdb sob3m sob3p
local bel4 fob4 fob6
local bel5 fob5 sob5 sob5m sob5p
local bel6 fob7 sob7 sob7m sob7p
local bel7 fob8 sob8 sob8m sob8p
local bel8 e501 e502 e503 e501b e504 e505 e506 e504b
local bel9 fob9

* All belief variables used in selection model
local bels `bel1' `bel2' `bel3' `bel4' `bel6' `bel7' `bel8' `bel9'

* Strata covariates (absorbed FE and used in models)
local strat inactiveF employedF fob2M

* Outcomes
local yvars job_search_123_w3 metas_laboral_w3_2 metas_laboral_w3_3

* Baseline controls (female already here)
local xvars female c1 c2_2_rp c3 c5 f6 age_dif  level_1 level_2 edu_WmoreH inactiveM unemployedM estrato_12 estrato_3 tec_2 


* Working control set for main outcome models
local vars_sample3 `xvars' `bel2' 

********************************************************************************
* TABLE 9. Employment – Baseline OLS, OLS+IPW, IPWRA (analytic SEs)
* Mirrors Table 6 structure. No D×Female interaction in OLS.
********************************************************************************
* Assumes from Table 6:
*   - xvars        : baseline controls (includes female)
*   - bels         : belief blocks for selection model
*   - vars_sample3 : working control set for outcomes
*   - strat        : strata FE
*   - $reps        : RITEST replications

********************************************************************************
* 1. Selection IPW weights for each sample used in Table 9
********************************************************************************
gen sample6 = 1 if sample4_none == 1 & sample5_ext == 1

local sample_list "sample2 sample3_ext sample4_any sample6"

foreach s of local sample_list {
    capture confirm variable `s'
    if _rc {
        di as error "Warning: sample indicator `s' not found; skipping weight estimation."
        continue
    }

    di as txt "Estimating selection weights for `s'"

    * Special case: sample2 – treat as no attrition ⇒ weight = 1
    if "`s'" == "sample2" {
        capture drop w_`s'
        gen double w_`s' = 1 if `s' < .
        continue
    }

    * Attrition samples: probit + IPW
    capture noisily probit `s' D `xvars' `bels' `strat', vce(cluster id)

    if _rc {
        di as error "Probit for `s' failed (r(`_rc')). Setting w_`s' = 1."
        capture drop w_`s'
        gen double w_`s' = 1 if `s' < .
    }
    else {
        capture drop ps_`s'
        capture drop w_`s'
        predict double ps_`s', pr
        gen double w_`s' = 1/ps_`s'
    }
}

********************************************************************************
* 2. Outcomes and main loop
********************************************************************************



eststo clear

* Follow your convention: j = 8, 9, 10 for these 3 outcomes
local j = 8

foreach y of local yvars {

    foreach i of numlist 2/5 {

        * Map sample index i -> sample indicator
        local sampvar ""
        if `i' == 2 local sampvar "sample2"
        if `i' == 3 local sampvar "sample3_ext"
        if `i' == 4 local sampvar "sample4_any"
        if `i' == 5 local sampvar "sample6"

        capture confirm variable `sampvar'
        if _rc continue   // skip if sample variable not present

        * Selection weight for this sample
        local wvar w_`sampvar'

        * Outcome with baseline control?
        local hasbaseline = 0
        if "`y'" == "job_search_123_w3" local hasbaseline = 1

        ****************************************************************
        * 2.1 BASELINE OLS (no selection weights) – pooled, male, female
        *     Stored as B`i'_`j'
        ****************************************************************

        * (a) Pooled OLS: y_w3 on D + controls (female is in `xvars`)
        if `hasbaseline' {
            reghdfe `y' D `vars_sample3' job_search_123 ///
                if `sampvar' == 1, absorb(`strat') vce(cluster id)
        }
        else {
            reghdfe `y' D `vars_sample3' ///
                if `sampvar' == 1, absorb(`strat') vce(cluster id)
        }

        scalar N_all = e(N)
        eststo B`i'_`j'

        * Means of Y by subgroup (unweighted)
        quietly summarize `y' if `sampvar' == 1
        scalar ymean_all  = r(mean)

        quietly summarize `y' if `sampvar' == 1 & female == 0
        scalar ymean_male = r(mean)

        quietly summarize `y' if `sampvar' == 1 & female == 1
        scalar ymean_fem  = r(mean)

        * (b) OLS – males only (unweighted)
        if `hasbaseline' {
            reghdfe `y' D `vars_sample3' job_search_123 ///
                if `sampvar' == 1 & female == 0, ///
                absorb(`strat') vce(cluster id)
        }
        else {
            reghdfe `y' D `vars_sample3' ///
                if `sampvar' == 1 & female == 0, ///
                absorb(`strat') vce(cluster id)
        }

        scalar N_male    = e(N)
        scalar b_D_male  = _b[D]
        scalar se_D_male = _se[D]
        scalar t_D_male  = b_D_male / se_D_male
        scalar p_D_male  = 2*(1 - normal(abs(t_D_male)))

        * (c) OLS – females only (unweighted)
        if `hasbaseline' {
            reghdfe `y' D `vars_sample3' job_search_123 ///
                if `sampvar' == 1 & female == 1, ///
                absorb(`strat') vce(cluster id)
        }
        else {
            reghdfe `y' D `vars_sample3' ///
                if `sampvar' == 1 & female == 1, ///
                absorb(`strat') vce(cluster id)
        }

        scalar N_fem    = e(N)
        scalar b_D_fem  = _b[D]
        scalar se_D_fem = _se[D]
        scalar t_D_fem  = b_D_fem / se_D_fem
        scalar p_D_fem  = 2*(1 - normal(abs(t_D_fem)))

        * (d) RITEST p-values for D: all, male, female
        scalar p_ri_all  = .
        scalar p_ri_male = .
        scalar p_ri_fem  = .

        * All
        if `hasbaseline' {
            capture noisily ritest D _b[D], ///
                cluster(id) strata(`strat') reps($reps) : ///
                reghdfe `y' D `vars_sample3' job_search_123 ///
                    if `sampvar' == 1, absorb(`strat') vce(cluster id)
        }
        else {
            capture noisily ritest D _b[D], ///
                cluster(id) strata(`strat') reps($reps) : ///
                reghdfe `y' D `vars_sample3' ///
                    if `sampvar' == 1, absorb(`strat') vce(cluster id)
        }
        if (_rc == 0) {
            matrix P_all = r(p)
            scalar p_ri_all = round(P_all[1,1], .001)
        }

        * Male
        if `hasbaseline' {
            capture noisily ritest D _b[D], ///
                cluster(id) strata(`strat') reps($reps) : ///
                reghdfe `y' D `vars_sample3' job_search_123 ///
                    if `sampvar' == 1 & female == 0, ///
                    absorb(`strat') vce(cluster id)
        }
        else {
            capture noisily ritest D _b[D], ///
                cluster(id) strata(`strat') reps($reps) : ///
                reghdfe `y' D `vars_sample3' ///
                    if `sampvar' == 1 & female == 0, ///
                    absorb(`strat') vce(cluster id)
        }
        if (_rc == 0) {
            matrix P_m = r(p)
            scalar p_ri_male = round(P_m[1,1], .001)
        }

        * Female
        if `hasbaseline' {
            capture noisily ritest D _b[D], ///
                cluster(id) strata(`strat') reps($reps) : ///
                reghdfe `y' D `vars_sample3' job_search_123 ///
                    if `sampvar' == 1 & female == 1, ///
                    absorb(`strat') vce(cluster id)
        }
        else {
            capture noisily ritest D _b[D], ///
                cluster(id) strata(`strat') reps($reps) : ///
                reghdfe `y' D `vars_sample3' ///
                    if `sampvar' == 1 & female == 1, ///
                    absorb(`strat') vce(cluster id)
        }
        if (_rc == 0) {
            matrix P_f = r(p)
            scalar p_ri_fem = round(P_f[1,1], .001)
        }

        * (e) Attach scalars to baseline OLS model B`i'_`j'
        estimates restore B`i'_`j'
        estadd scalar N_all      = N_all,      replace
        estadd scalar N_male     = N_male,     replace
        estadd scalar N_fem      = N_fem,      replace

        estadd scalar ymean_all  = ymean_all,  replace
        estadd scalar ymean_male = ymean_male, replace
        estadd scalar ymean_fem  = ymean_fem,  replace

        estadd scalar b_D_male   = b_D_male,   replace
        estadd scalar se_D_male  = se_D_male,  replace
        estadd scalar p_D_male   = p_D_male,   replace

        estadd scalar b_D_fem    = b_D_fem,    replace
        estadd scalar se_D_fem   = se_D_fem,   replace
        estadd scalar p_D_fem    = p_D_fem,    replace

        estadd scalar p_ri_all   = p_ri_all,   replace
        estadd scalar p_ri_male  = p_ri_male,  replace
        estadd scalar p_ri_fem   = p_ri_fem,   replace
        eststo B`i'_`j'

        ****************************************************************
        * 2.2 OLS WITH SELECTION IPW – pooled, male, female
        *     Stored as O`i'_`j'
        ****************************************************************

        * (a) Pooled weighted OLS
        if `hasbaseline' {
            reghdfe `y' D `vars_sample3' job_search_123 ///
                if `sampvar' == 1 [pweight = `wvar'], ///
                absorb(`strat') vce(cluster id)
        }
        else {
            reghdfe `y' D `vars_sample3' ///
                if `sampvar' == 1 [pweight = `wvar'], ///
                absorb(`strat') vce(cluster id)
        }

        scalar N_all_w = e(N)
        eststo O`i'_`j'

        * Weighted means of Y
        quietly summarize `y' [aweight = `wvar'] if `sampvar' == 1
        scalar ymean_all_w  = r(mean)

        quietly summarize `y' [aweight = `wvar'] if `sampvar' == 1 & female == 0
        scalar ymean_male_w = r(mean)

        quietly summarize `y' [aweight = `wvar'] if `sampvar' == 1 & female == 1
        scalar ymean_fem_w  = r(mean)

        * (b) Weighted OLS – males
        if `hasbaseline' {
            reghdfe `y' D `vars_sample3' job_search_123 ///
                if `sampvar' == 1 & female == 0 [pweight = `wvar'], ///
                absorb(`strat') vce(cluster id)
        }
        else {
            reghdfe `y' D `vars_sample3' ///
                if `sampvar' == 1 & female == 0 [pweight = `wvar'], ///
                absorb(`strat') vce(cluster id)
        }

        scalar N_male_w    = e(N)
        scalar b_D_male_w  = _b[D]
        scalar se_D_male_w = _se[D]
        scalar t_D_male_w  = b_D_male_w / se_D_male_w
        scalar p_D_male_w  = 2*(1 - normal(abs(t_D_male_w)))

        * (c) Weighted OLS – females
        if `hasbaseline' {
            reghdfe `y' D `vars_sample3' job_search_123 ///
                if `sampvar' == 1 & female == 1 [pweight = `wvar'], ///
                absorb(`strat') vce(cluster id)
        }
        else {
            reghdfe `y' D `vars_sample3' ///
                if `sampvar' == 1 & female == 1 [pweight = `wvar'], ///
                absorb(`strat') vce(cluster id)
        }

        scalar N_fem_w    = e(N)
        scalar b_D_fem_w  = _b[D]
        scalar se_D_fem_w = _se[D]
        scalar t_D_fem_w  = b_D_fem_w / se_D_fem_w
        scalar p_D_fem_w  = 2*(1 - normal(abs(t_D_fem_w)))

        * (d) Attach scalars to weighted OLS model O`i'_`j'
        estimates restore O`i'_`j'
        estadd scalar N_all      = N_all_w,      replace
        estadd scalar N_male     = N_male_w,     replace
        estadd scalar N_fem      = N_fem_w,      replace

        estadd scalar ymean_all  = ymean_all_w,  replace
        estadd scalar ymean_male = ymean_male_w, replace
        estadd scalar ymean_fem  = ymean_fem_w,  replace

        estadd scalar b_D_male   = b_D_male_w,   replace
        estadd scalar se_D_male  = se_D_male_w,  replace
        estadd scalar p_D_male   = p_D_male_w,   replace

        estadd scalar b_D_fem    = b_D_fem_w,    replace
        estadd scalar se_D_fem   = se_D_fem_w,   replace
        estadd scalar p_D_fem    = p_D_fem_w,    replace
        eststo O`i'_`j'

        ****************************************************************
        * 2.3 IPWRA – ATT/PO for All, Male, Female (analytic SEs)
        *     Uses selection weights; stored as T`i'_`j'
        ****************************************************************

        * (a) All
        if `hasbaseline' {
            teffects ipwra (`y' job_search_123 `strat') ///
                           (D `vars_sample3' `strat') ///
                           if `sampvar' == 1 [pweight = `wvar'], ///
                           atet vce(cluster id)
        }
        else {
            teffects ipwra (`y' `strat') ///
                           (D `vars_sample3' `strat') ///
                           if `sampvar' == 1 [pweight = `wvar'], ///
                           atet vce(cluster id)
        }

        matrix bA = e(b)
        matrix VA = e(V)

        scalar ATET_all    = bA[1,1]
        scalar ATET_se_all = sqrt(VA[1,1])
        scalar ATET_pv_all = 2*(1 - normal(abs(ATET_all/ATET_se_all)))

        scalar PO_all      = bA[1,2]
        scalar PO_se_all   = sqrt(VA[2,2])
        scalar PO_pv_all   = 2*(1 - normal(abs(PO_all/PO_se_all)))

        * (b) Male
        if `hasbaseline' {
            teffects ipwra (`y' job_search_123 `strat') ///
                           (D `vars_sample3' `strat') ///
                           if female == 0 & `sampvar' == 1 [pweight = `wvar'], ///
                           atet vce(cluster id)
        }
        else {
            teffects ipwra (`y' `strat') ///
                           (D `vars_sample3' `strat') ///
                           if female == 0 & `sampvar' == 1 [pweight = `wvar'], ///
                           atet vce(cluster id)
        }

        matrix bA = e(b)
        matrix VA = e(V)

        scalar ATET_male    = bA[1,1]
        scalar ATET_se_male = sqrt(VA[1,1])
        scalar ATET_pv_male = 2*(1 - normal(abs(ATET_male/ATET_se_male)))

        scalar PO_male      = bA[1,2]
        scalar PO_se_male   = sqrt(VA[2,2])
        scalar PO_pv_male   = 2*(1 - normal(abs(PO_male/PO_se_male)))

        * (c) Female
        if `hasbaseline' {
            teffects ipwra (`y' job_search_123 `strat') ///
                           (D `vars_sample3' `strat') ///
                           if female == 1 & `sampvar' == 1 [pweight = `wvar'], ///
                           atet vce(cluster id)
        }
        else {
            teffects ipwra (`y' `strat') ///
                           (D `vars_sample3' `strat') ///
                           if female == 1 & `sampvar' == 1 [pweight = `wvar'], ///
                           atet vce(cluster id)
        }

        matrix bA = e(b)
        matrix VA = e(V)

        scalar ATET_fem    = bA[1,1]
        scalar ATET_se_fem = sqrt(VA[1,1])
        scalar ATET_pv_fem = 2*(1 - normal(abs(ATET_fem/ATET_se_fem)))

        scalar PO_fem      = bA[1,2]
        scalar PO_se_fem   = sqrt(VA[2,2])
        scalar PO_pv_fem   = 2*(1 - normal(abs(PO_fem/PO_se_fem)))

        * (d) Create IPWRA container: copy weighted OLS and attach ATT/PO
        estimates restore O`i'_`j'
        eststo T`i'_`j'

        estimates restore T`i'_`j'
        estadd scalar ATET_all    = ATET_all,    replace
        estadd scalar ATET_se_all = ATET_se_all, replace
        estadd scalar ATET_pv_all = ATET_pv_all, replace

        estadd scalar PO_all      = PO_all,      replace
        estadd scalar PO_se_all   = PO_se_all,   replace
        estadd scalar PO_pv_all   = PO_pv_all,   replace

        estadd scalar ATET_male    = ATET_male,    replace
        estadd scalar ATET_se_male = ATET_se_male, replace
        estadd scalar ATET_pv_male = ATET_pv_male, replace

        estadd scalar PO_male      = PO_male,      replace
        estadd scalar PO_se_male   = PO_se_male,   replace
        estadd scalar PO_pv_male   = PO_pv_male,   replace

        estadd scalar ATET_fem     = ATET_fem,     replace
        estadd scalar ATET_se_fem  = ATET_se_fem,  replace
        estadd scalar ATET_pv_fem  = ATET_pv_fem,  replace

        estadd scalar PO_fem       = PO_fem,       replace
        estadd scalar PO_se_fem    = PO_se_fem,    replace
        estadd scalar PO_pv_fem    = PO_pv_fem,    replace
        eststo T`i'_`j'
    }

    local j = `j' + 1
}

********************************************************************************
* 3. EXPORT TABLES 9A (Baseline OLS), 9B (OLS+IPW), 9C (IPWRA)
********************************************************************************

* Column mapping (same as your previous FINAL version):
* col 1 = sample3_ext  (i=3, j=8)  -> *_3_8
* col 2 = sample4_any  (i=4, j=8)  -> *_4_8
* col 3 = sample5_ext  (i=5, j=8)  -> *_5_8
* col 4 = sample3_ext  (i=3, j=9)  -> *_3_9
* col 5 = sample2      (i=2, j=9)  -> *_2_9
* col 6 = sample3_ext  (i=3, j=10) -> *_3_10
* col 7 = sample2      (i=2, j=10) -> *_2_10

*----------------------------------------------------
* 9A. Baseline OLS (no selection weights)
*----------------------------------------------------
#delimit ;
local opts9_ols_base style(tex)  
  varlabels(_cons Constant D "Treatment") 
  cells(b(star fmt(%9.3f)) se(par)) 
  stats(N_all N_male N_fem 
        ymean_all ymean_male ymean_fem
        b_D_male se_D_male p_D_male
        b_D_fem  se_D_fem  p_D_fem
        p_ri_all p_ri_male p_ri_fem,
        fmt(%9.3f)
        label("N (All)" 
              "N (Male)"
              "N (Female)"
              "Mean Dep. Var (All)"
              "Mean Dep. Var (Male)"
              "Mean Dep. Var (Female)"
              "OLS β(D) Male"    "OLS SE Male"    "OLS p-val Male"
              "OLS β(D) Female"  "OLS SE Female"  "OLS p-val Female"
              "RI p-val D (All)" "RI p-val D (Male)" "RI p-val D (Female)")) 
  label collabels(none) msign(--) nolz varwidth(1) modelwidth(16) 
  starlevels(* 0.10 ** 0.05 *** 0.01)
;
#delimit cr

estout B3_8 B4_8 B5_8 B3_9 B2_9 B3_10 B2_10 ///
    using "Tables/Table9_Employment_OLS_baseline.tex", replace `opts9_ols_base' margin

*----------------------------------------------------
* 9B. OLS with selection IPW weights
*----------------------------------------------------
#delimit ;
local opts9_ols_ipw style(tex)  
  varlabels(_cons Constant D "Treatment") 
  cells(b(star fmt(%9.3f)) se(par)) 
  stats(N_all N_male N_fem 
        ymean_all ymean_male ymean_fem
        b_D_male se_D_male p_D_male
        b_D_fem  se_D_fem  p_D_fem,
        fmt(%9.3f)
        label("N (All)" 
              "N (Male)"
              "N (Female)"
              "Mean Dep. Var (All, weighted)"
              "Mean Dep. Var (Male, weighted)"
              "Mean Dep. Var (Female, weighted)"
              "OLS-IPW β(D) Male"    "OLS-IPW SE Male"    "OLS-IPW p-val Male"
              "OLS-IPW β(D) Female"  "OLS-IPW SE Female"  "OLS-IPW p-val Female")) 
  label collabels(none) msign(--) nolz varwidth(1) modelwidth(16) 
  starlevels(* 0.10 ** 0.05 *** 0.01)
;
#delimit cr

estout O3_8 O4_8 O5_8 O3_9 O2_9 O3_10 O2_10 ///
    using "Tables/Table9_Employment_OLS_IPW.tex", replace `opts9_ols_ipw' margin

*----------------------------------------------------
* 9C. IPWRA (analytic SEs) – ATT/PO by group
*     Coefficient panel: only D
*----------------------------------------------------
#delimit ;
local opts9_ipwra style(tex)  
  cells(b(star fmt(%9.3f)) se(par)) 
  stats(ATET_all ATET_se_all ATET_pv_all 
        PO_all   PO_se_all   PO_pv_all
        ATET_male ATET_se_male ATET_pv_male
        PO_male   PO_se_male   PO_pv_male
        ATET_fem  ATET_se_fem  ATET_pv_fem
        PO_fem    PO_se_fem    PO_pv_fem,
        fmt(%9.3f)
        label("ATT All"      "Std. Err. ATT All"   "P-value ATT All"
              "PO All"       "Std. Err. PO All"    "P-value PO All"
              "ATT Male"     "Std. Err. ATT Male"  "P-value ATT Male"
              "PO Male"      "Std. Err. PO Male"   "P-value PO Male"
              "ATT Female"   "Std. Err. ATT Female""P-value ATT Female"
              "PO Female"    "Std. Err. PO Female" "P-value PO Female")) 
  label collabels(none) msign(--) nolz varwidth(1) modelwidth(16) 
  starlevels(* 0.10 ** 0.05 *** 0.01)
;
#delimit cr

estout T3_8 T4_8 T5_8 T3_9 T2_9 T3_10 T2_10 ///
    using "Tables/Table9_Employment_IPWRA.tex", replace `opts9_ipwra' margin ///
    keep(D) varlabels(D "Treatment")

